<script setup>
import {onMounted, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import axios from "axios";
import qs from "qs";

document.title = 'MMD模型资源管理中心 - 授权管理'

const codeList = ref([])
const totalCode = ref(0); // 从API响应中获取总数
const currentPage = ref(1);
const pageSize = ref(10);

const copyCode = (code) => {
  navigator.clipboard.writeText(code)
      .then(() => { ElMessage.success("复制成功!!") })
      .catch(() => { ElMessage.error("复制失败!!") })
}

const getCodeList = async () => {
  try {
    const res = await axios.get("/api/v2/code/list",{
      params: { page: currentPage.value, size: pageSize.value }
    })
    let payload = res && res.data ? res.data : null
    // 兼容后端返回字符串的情况
    if (typeof payload === 'string') {
      try { payload = JSON.parse(payload) } catch (_) {}
    }
    let pageData = payload && payload.data ? payload.data : null
    if (typeof pageData === 'string') {
      try { pageData = JSON.parse(pageData) } catch (_) {}
    }
    const rawList = (pageData && pageData.data) || (pageData && pageData.records) || (pageData && pageData.list) || []
    const listArr = Array.isArray(rawList) ? rawList : []
    // 规范化字段：兼容后端大写键 CId/CCode/CStatus
    const normalized = listArr.map((it)=>({
      cId: it.cId ?? it.CId ?? it.cid ?? it.id,
      cCode: it.cCode ?? it.CCode ?? it.ccode ?? it.code,
      cStatus: it.cStatus ?? it.CStatus ?? it.cstatus ?? it.status
    }))
    codeList.value = normalized
    const totalVal = pageData && pageData.total
    const parsedTotal = typeof totalVal === 'string' ? Number(totalVal) : totalVal
    totalCode.value = Number.isFinite(parsedTotal) ? parsedTotal : codeList.value.length
  }catch (e){
    console.log('API不可用，使用模拟数据')
    generateMockData()
  }
}

// 生成模拟数据用于测试
const generateMockData = () => {
  const mockData = []
  const statuses = [0, 1]
  for (let i = 1; i <= 156; i++) {
    const charStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let randomCode = ''
    for (let j = 0; j < 18; j++) {
      const randomIndex = Math.floor(Math.random() * charStr.length)
      randomCode += charStr.charAt(randomIndex)
    }
    mockData.push({ cId: i, cCode: randomCode, cStatus: statuses[Math.floor(Math.random() * statuses.length)] })
  }
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  codeList.value = mockData.slice(start, end)
  totalCode.value = mockData.length
}

const addCode = async () => {
  const charStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let randomCode = '';
  for (let i = 0; i < 18; i++) {
    const randomIndex = Math.floor(Math.random() * charStr.length);
    randomCode += charStr.charAt(randomIndex);
  }
  try {
    const res = await axios.post("/api/v2/code/add", null, { params: { cCode: randomCode }})
    if (res.data.code === 200) {
      ElMessage.success("新增成功!");
      await getCodeList()
    } else {
      ElMessage.error(res.data.msg || "新增失败!!")
    }
  }catch (e){
    ElMessage.error(`服务器错误!请与管理员联系！错误: ${e.message}`)
  }
}

const deleteCode = async (row) => {
  ElMessageBox.confirm(`确定删除授权码 ${row.cCode} 吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    const res = await axios.delete(`/api/v2/code/${row.cId}`)
    if (res.data.code === 200) {
      ElMessage.success('删除成功！')
      await getCodeList()
    } else {
      ElMessage.error(res.data.msg || '删除失败！')
    }
  }).catch(() => {})
}

const handleCurrentChange = (newPage) => { currentPage.value = newPage; getCodeList() };
const handleSizeChange = (newSize) => { pageSize.value = newSize; currentPage.value = 1; getCodeList() };

onMounted(()=>{ getCodeList() })
</script>

<template>
  <div class="code-management-container">
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1 class="page-title">授权管理</h1>
          <p class="page-subtitle">管理MMD模型访问授权码</p>
        </div>
        <div class="header-right">
          <el-button type="primary" icon="Plus" size="large" class="add-button" @click="addCode">新增授权码</el-button>
        </div>
      </div>
    </div>

    <div class="statistics-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon"><el-icon><Key /></el-icon></div>
            <div class="stat-content">
              <div class="stat-number">{{ totalCode }}</div>
              <div class="stat-label">授权码总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon"><el-icon><CircleCheck /></el-icon></div>
            <div class="stat-content">
              <div class="stat-number">{{ codeList.filter(item => item.cStatus === 0).length }}</div>
              <div class="stat-label">未使用</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-icon"><el-icon><CircleClose /></el-icon></div>
            <div class="stat-content">
              <div class="stat-number">{{ codeList.filter(item => item.cStatus === 1).length }}</div>
              <div class="stat-label">已使用</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="table-section">
      <div class="table-card">
        <div class="table-header">
          <h3 class="table-title">授权码列表</h3>
          <div class="table-actions">
            <el-button icon="Refresh" size="small" @click="getCodeList">刷新</el-button>
          </div>
        </div>
        
        <el-table :data="codeList" class="data-table" stripe border>
          <el-table-column align="center" prop="cId" label="授权码ID" width="120" />
          <el-table-column align="center" prop="cCode" label="授权码" min-width="200" show-overflow-tooltip />
          <el-table-column align="center" prop="cStatus" label="授权码状态" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.cStatus === 1" type="danger" effect="dark">已使用</el-tag>
              <el-tag v-else type="success" effect="dark">未使用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" @click="copyCode(scope.row.cCode)" :disabled="scope.row.cStatus === 1" icon="CopyDocument">复制</el-button>
              <el-button type="danger" size="small" @click="deleteCode(scope.row)" icon="Delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :background="true"
            :page-sizes="[10, 20, 50, 100]"
            :total="totalCode"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.code-management-container {
  min-height: 100%;
}

/* 页面头部 */
.page-header {
  margin-bottom: 2rem;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  background: var(--gradient-card);
  border-radius: 12px;
  border: 1px solid var(--border-gold);
  box-shadow: 0 4px 12px var(--shadow-dark);
}

.page-title {
  margin: 0;
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--gold-primary);
  background: var(--gradient-gold);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.page-subtitle {
  margin: 0.5rem 0 0 0;
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.add-button {
  background: var(--gradient-gold) !important;
  border: none !important;
  color: var(--primary-black) !important;
  font-weight: 600 !important;
  transition: all 0.3s ease !important;
}

.add-button:hover {
  transform: translateY(-2px) !important;
  box-shadow: 0 8px 20px var(--shadow-gold) !important;
}

/* 统计卡片 */
.statistics-section {
  margin-bottom: 2rem;
}

.stat-card {
  background: var(--gradient-card);
  border: 1px solid var(--border-gold);
  border-radius: 12px;
  padding: 1.5rem;
  display: flex;
  align-items: center;
  gap: 1rem;
  box-shadow: 0 4px 12px var(--shadow-dark);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px var(--shadow-gold);
}

.stat-icon {
  width: 60px;
  height: 60px;
  background: var(--gradient-gold);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-black);
  font-size: 1.5rem;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 2rem;
  font-weight: 700;
  color: var(--gold-primary);
  line-height: 1;
  margin-bottom: 0.5rem;
}

.stat-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

/* 表格区域 */
.table-section {
  margin-bottom: 2rem;
}

.table-card {
  background: var(--gradient-card);
  border: 1px solid var(--border-gold);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px var(--shadow-dark);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid var(--border-dark);
}

.table-title {
  margin: 0;
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--text-primary);
}

.data-table {
  width: 100%;
}

.pagination-wrapper {
  padding: 1.5rem;
  display: flex;
  justify-content: center;
  border-top: 1px solid var(--border-dark);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .statistics-section .el-col {
    margin-bottom: 1rem;
  }
  
  .table-header {
    flex-direction: column;
    gap: 1rem;
  }
}
</style>